package com.example.springbootgraduation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootgraduation.entity.BanJi;
import com.example.springbootgraduation.entity.Teacher;
import com.example.springbootgraduation.entity.User;
import com.example.springbootgraduation.entity.XueYuan;
import com.example.springbootgraduation.service.*;
import com.example.springbootgraduation.vo.DataView;
import com.example.springbootgraduation.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

//用户
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private BanJiService banJiService;

    @Autowired
    private XueYuanService xueYuanService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private RoleService roleService;

    /**
     * 跳转user页面
     * @return
     */
    @RequestMapping("/toUser")
    public String toUser(){
        return "user/user";
    }

    /**
     * 跳转修改密码
     */
    @RequestMapping("/toChangePassword")
    public String toChangePassword(){
        return "user/changepassword";
    }

    /**
     * 跳转个人修改页面
     */
    @RequestMapping("/toUserInfo")
    public String toUserInfo(){
        return "user/userInfo";
    }

    /**
     * 带有模糊查询条件查询用户所有数据
     */
    @RequestMapping("/loadAllUser")
    @ResponseBody
    public DataView loadAllUser(UserVo userVo){
//        第一张办法(关联查询)
//        if (StringUtils.isNoneBlank(userVo.getUsername())){
//            userService.loadUserByLeftJoin(userVo.getUsername(),userVo.getPage(),userVo.getLimit());
//        }
//        mapper中定义SQL语句
//        @Select("SELECT a.username,b.name FROM user as a where a.username=#{} LEFT JOIN ban_ji as b ON a.ban_ji_id = b.id limit #{} #{}");

//        第二种方法 先查询所有的数据 1 1 1
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        IPage<User> page = new Page<>(userVo.getPage(),userVo.getLimit());
        //构造查询条件
        queryWrapper.like(StringUtils.isNoneBlank(userVo.getUsername()),"username",userVo.getUsername());
        queryWrapper.like(StringUtils.isNoneBlank(userVo.getPhone()),"phone",userVo.getPhone());
        IPage<User> iPage = userService.page(page, queryWrapper);
        for (User user : iPage.getRecords()){//getRecords所有的user
            /*先查询ipage对象*/
            /*为班级名字进行赋值*/
            if (user.getBanJiId()!=null){
                /*班级Service查库*/
                BanJi banji = banJiService.getById(user.getBanJiId());//查询到id
                user.setBanJiName(banji.getName());//根据找到班级名字
            }
            /*为学院名字进行赋值*/
            if (user.getXueYuanId()!=null){
                XueYuan xueYuan = xueYuanService.getById(user.getXueYuanId());
                user.setXueYuanName(xueYuan.getName());
            }
            /*为老师名字进行赋值*/
            if (user.getTeacherId()!=null){
                Teacher teacher = teacherService.getById(user.getTeacherId());
                user.setTeacherName(teacher.getName());
            }
        }

        return new DataView(iPage.getTotal(),iPage.getRecords());
    }

    /**
     * 新增用户
     */
    @RequestMapping("/addUser")
    @ResponseBody
    public DataView addUser(User user){
        userService.save(user);
        DataView dataView = new DataView();
        dataView.setMsg("添加用户成功！");
        dataView.setCode(200);
        return dataView;
    }

    /**
     * 修改用户
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public DataView updateUser(User user){
        userService.updateById(user);
        DataView dataView = new DataView();
        dataView.setMsg("修改用户成功！");
        dataView.setCode(200);
        return dataView;
    }

    /**
     * 删除用户
     */
    @RequestMapping("/deleteUser/{id}")
    @ResponseBody
    public DataView deleteUser(@PathVariable("id") Integer id){//@PathVariable("id")取路径上的id
        userService.removeById(id);
        DataView dataView = new DataView();
        dataView.setMsg("删除用户成功！");
        dataView.setCode(200);
        return dataView;
    }

    /**
     * 初始化下列列表的数据【学院】
     */
    @RequestMapping("/listAllBanJi")
    @ResponseBody
    public List<BanJi> listAllBanJi(){
        List<BanJi> list = banJiService.list();
        return list;
    }

    /**
     * 初始化下列列表的数据【班级】
     */
    @RequestMapping("/listAllXueYuan")
    @ResponseBody
    public List<XueYuan> listAllXueYuan(){
        List<XueYuan> list = xueYuanService.list();
        return list;
    }

    /**
     * 初始化下列列表的数据【老师】
     */
    @RequestMapping("/listAllTeacher")
    @ResponseBody
    public List<Teacher> listAllTeacher(){
        List<Teacher> list = teacherService.list();
        return list;
    }

    /**
     * 重置密码
     */
    @RequestMapping("/resetPwd/{id}")
    @ResponseBody
    public DataView resetPwd(@PathVariable("id") Integer id){
        User user = new User();
        user.setId(id);
        user.setPassword("123456");//设置初始值
        userService.updateById(user);
        DataView dataView = new DataView();
        dataView.setMsg("重置密码成功！");
        dataView.setCode(200);
        return dataView;
    }

    /**
     * 点击【分配角色】时，初始化用户的角色列表
     * 打开分配角色的弹出层
     * 根据Id查询所拥有的角色
     */
    @RequestMapping("/initRoleByUserId")
    @ResponseBody
    public DataView initRoleByUserId(Integer id){
        /*查询角色*/
        List<Map<String, Object>> listMaps = roleService.listMaps();
        /*查询当前登录用户所拥有的角色*/
        List<Integer> currentUserRoleIds = roleService.queryUserRoleById(id);
        /*进行赋值,让前端，变为选中状态*/
        for (Map<String,Object> map : listMaps){
            Boolean LAY_CHECKED=false;//默认么有选中
            Integer roleId = (Integer) map.get("id");
            for (Integer rid : currentUserRoleIds){//对rid进行遍历
                if (rid.equals(roleId)){
                    LAY_CHECKED = true;
                    break;
                }
            }
            map.put("LAY_CHECKED",LAY_CHECKED);//map已经填充进去
        }
        return new DataView(Long.valueOf(listMaps.size()),listMaps);
    }

    /**
     * 保存用户与角色之间的关系 【一对多关系】
     * 先删除再保存关系
     */
    @RequestMapping("/saveUserRole")
    @ResponseBody
    public DataView saveUserRole(Integer uid,Integer[] ids){//uid：用户id，ids：角色id数组
        userService.saveUserRole(uid,ids);
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("用户的角色分配成功！");
        return dataView;
    }
}
